package cn.clq.basic.service.impl;

import cn.clq.basic.constant.Constant;
import cn.clq.basic.dto.LoginDto;
import cn.clq.basic.dto.WeChatDto;
import cn.clq.basic.exception.BusinessException;
import cn.clq.basic.service.ILoginService;
import cn.clq.basic.util.AjaxResult;
import cn.clq.basic.util.HttpClientUtils;
import cn.clq.basic.util.MD5Utils;
import cn.clq.basic.util.StrUtils;
import cn.clq.basic.util.jwt.JwtUtils;
import cn.clq.basic.util.jwt.LoginSuccessDto;
import cn.clq.basic.util.jwt.Playload;
import cn.clq.basic.util.jwt.RsaUtils;
import cn.clq.system.domain.Menu;
import cn.clq.system.mapper.MenuMapper;
import cn.clq.system.mapper.PermissionMapper;
import cn.clq.user.domain.Logininfo;
import cn.clq.user.domain.User;
import cn.clq.user.domain.Wxuser;
import cn.clq.user.mapper.LogininfoMapper;
import cn.clq.user.mapper.UserMapper;
import cn.clq.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author clqlongbao
 * @version 1.0
 * @description: TODO
 * @date 2022/6/18 17:25
 */
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    /**
     * @description: 账号密码登录
     * @param: dto
     * @return:
     * @author clqlongbao
     * @date: 2022/6/19 17:57
     */
    @Override
    public Map<String, Object> account(LoginDto dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();
        Integer type = dto.getType();

        //1.空校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(type)) {
            throw new BusinessException("请填写完整的登录信息");
        }
        //2.账号校验
        //2.1从数据库中查询用户信息
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username, type);
        if (logininfo == null) {
            throw new BusinessException("账号不存在");
        }
        //3.密码校验
        //3.1将用户输入的密码通过数据库的盐值加密之后，再与数据库的密码进行比对
        String salt = logininfo.getSalt();
        String md5Pwd = MD5Utils.encrypByMd5(password + salt);
        if (!md5Pwd.equals(logininfo.getPassword())) {
            throw new BusinessException("密码错误");
        }
        return LoginSuccessHandler(logininfo);
    }

//        //4.保存到redis
//        //4.1生成token
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        //5.返回token和logininfo
//        //5.1不能将敏感信息返回给前端
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);
//        Map<String, Object> map = new HashMap<>();
//        map.put("logininfo",logininfo);
//        map.put("token",token);
//        return map;
    /**
     * @description: 登陆成功之后的处理
     * @param: logininfo
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     * @author clqlongbao
     * @date: 2022/6/23 18:05
     */
    @SneakyThrows
    public Map<String,Object> LoginSuccessHandler(Logininfo logininfo){
        //还需要在这里进行权限判断
        //0.new一个LoginSuccessDto对象用于传递登录之后需要向前端返回的结果
        LoginSuccessDto loginSuccessDto = new LoginSuccessDto();
        loginSuccessDto.setLogininfo(logininfo);
        //1.判断是否是员工，用户放行，员工判断
        if (logininfo.getType() == Constant.PersionType.EMPLOYEE) {
            //2.查询对应的菜单权限和按钮权限
            List<Menu> menus = menuMapper.loadMenusByLogininfoId(logininfo.getId());
            List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
            loginSuccessDto.setMenus(menus);
            loginSuccessDto.setPermissions(permissions);
        }
        //3.将登陆人信息+权限封装成jwt串
        //3.1获取私钥
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile());
        //3.2使用私钥将登陆结果加密成jwt串
        String jwtStr = JwtUtils.generateTokenExpireInMinutes(loginSuccessDto, privateKey, 30);
        //3.3还要使用map返回明文
        Map<String, Object> map = new HashMap<>();
        map.put("token",jwtStr);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        map.put("menus",loginSuccessDto.getMenus());
        map.put("permissions",loginSuccessDto.getPermissions());
        return map;
    }
    /**
     * @description: 首次扫码跳转到账号绑定页面，后续扫码直接免密登录
     * @param: dto
     * @return: cn.clq.basic.util.AjaxResult
     * @author clqlongbao
     * @date: 2022/6/19 19:48
     */
    @Override
    public AjaxResult wechat(WeChatDto dto) {
//      1.拼接通过code从微信获取token+openid的链接       ②
        String tokenUrl = Constant.WeChat.TOKEN_URL
                .replace("APPID",Constant.WeChat.APPID)
                .replace("SECRET",Constant.WeChat.SECRET)
                .replace("CODE",dto.getCode());
        //发起请求，获取带有token+openid值的json格式的字符串
        String tokenStr  = HttpClientUtils.httpGet(tokenUrl);
        //将字符串转化为json对象
        JSONObject tokenObj = JSONObject.parseObject(tokenStr);
        //获取属性值
        String accessToken = tokenObj.getString("access_token");
        String openid = tokenObj.getString("openid");
//      2.通过openid查询t_wxuser表，判断是否wxuser存在并且user_id不为空
        Wxuser wxuser = wxuserMapper.loadByOpenId(openid);
//       2.1 有，且userId存在，直接免密登录===第二次之后的扫码登录
        if(wxuser!=null && wxuser.getUserId()!=null){
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            return AjaxResult.me().setResultObj(LoginSuccessHandler(logininfo));
//            //将数据存储到Redis
//            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
//            String token = UUID.randomUUID().toString();
//            redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
//            //将token和logininfo返回给前端
//            Map<String, Object> map = new HashMap<>();
//            map.put("token",token);
//            //不要将敏感信息返回给前端
//            logininfo.setSalt(null);
//            logininfo.setPassword(null);
//            map.put("logininfo",logininfo);
//            return AjaxResult.me().setResultObj(map);
        }
//       2.2 没有，这里应该让浏览器跳转到绑定页面，让它自己输入账号和密码来完成绑定,还要返回token和openId,用于拼接绑定页面的地址
        String binderParams = "?access_token="+accessToken+"&openid="+openid;
        return AjaxResult.me().setSuccess(false).setResultObj(binderParams);
    }

    /**
     * @description: 微信绑定账号
     * @param: dto
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     * @author clqlongbao
     * @date: 2022/6/19 20:04
     */
    @Override
    public Map<String, Object> binder(WeChatDto dto) {
//      1.根据username 查询t_user是否曾今已经存在
        User user = userMapper.loadByPhone(dto.getPhone());
        Logininfo logininfo =null;
        if(user!=null){
//      1.1 存在 查询出来，等着绑定
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }else{
//      1.2 不存在 生成新的t_user + t_logininfo
            user = dto2User(dto);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
//      2.根据token + openid 去微信查询微信的用户基本信息   ③
        String wxuserUrl =Constant.WeChat.WXUSER_URL
                .replace("ACCESS_TOKEN",dto.getAccessToken())
                .replace("OPENID",dto.getOpenId());
        //获取到一长串的个人信息
        String wxuserStr = HttpClientUtils.httpGet(wxuserUrl);
//      3.根据微信的用户基本信息生成t_wxuser对象
        Wxuser wxuser = JSONObject.parseObject(wxuserStr, Wxuser.class);
//      4.t_wxuser绑定t_user
        wxuser.setUserId(user.getId());
//      5.保存t_wxuser（完成了整个绑定流程）
        wxuserMapper.save(wxuser);
//      6.直接免密登录
        return LoginSuccessHandler(logininfo);
//        //将数据存储到Redis
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
//        //将token和logininfo返回给前端
//        Map<String, Object> map = new HashMap<>();
//        map.put("token",token);
//        //不要将敏感信息返回给前端
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);
//        map.put("logininfo",logininfo);
//        return map;
    }

    //将dto转换成user对象，然后加密保存
    private User dto2User(WeChatDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        //获得盐值
        String salt = StrUtils.getComplexRandomString(32);
        //对密码进行加密加盐
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }
    //同步修改t_logininfo表
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //拷贝同名字段的值(old,new)
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(Constant.PersionType.USER);//手动设置用户类型
        return logininfo;
    }
}
